package com.ezlcp.user.controller;

import com.alibaba.fastjson2.JSONArray;
import com.ezlcp.commons.base.db.BaseService;
import com.ezlcp.commons.base.entity.JsonResult;
import com.ezlcp.commons.base.search.QueryFilter;
import com.ezlcp.commons.constant.Constants;
import com.ezlcp.commons.constant.GroupTypeEnum;
import com.ezlcp.commons.constant.StatusEnum;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.ContextUtil;
import com.ezlcp.user.entity.Group;
import com.ezlcp.user.service.GroupServiceImpl;
import com.ezlcp.user.service.LogService;
import com.ezlcp.user.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/ezlcp/user/group")
@Tag(name = "用户组")
public class GroupController extends BaseController<Group> {
    @Autowired
    @Lazy
    GroupServiceImpl groupService;

    @Resource
    private LogService logService;

    @Operation(summary = "获取用户组类型")
    @GetMapping("/getGroupType")
    public JsonResult getGroupType() {
        JsonResult result = JsonResult.getSuccessResult("common.handleSuccess");
        var types = GroupTypeEnum.values();
        JSONArray array = new JSONArray();
        for (var type : types) {
            array.add(type.toJsonObject());
        }
        result.setData(array);
        return result;
    }

    @Operation(summary = "f.可选择的父级节点列表,如果groupId不存在可以传NULL")
    @PostMapping("/selectParentGroups")
    public JsonResult selectParentGroups(@Parameter(description = "当前组Id") @RequestParam(value = "groupId", required = false) String groupId,
                                         @Parameter(description = "当前组类型") @RequestParam(value = "groupType") Integer groupType) {
        JsonResult result = JsonResult.getSuccessResult("common.handleSuccess");
        var data = groupService.selectParentGroups(groupId, GroupTypeEnum.valueOf(groupType));
        result.setData(data);
        return result;
    }

    @Operation(summary = "a.获取某用户的全部用户组")
    @PostMapping("/getUserGroups")
    public JsonResult getUserGroups(@Parameter(description = "用户ID") @RequestParam(value = "userId") String userId) {
        if (StringUtils.isEmpty(userId)) {
            return JsonResult.Fail("common.paramError");
        }
        JsonResult result = JsonResult.Success("common.handleSuccess");
        result.setShow(false);
        Object data = groupService.getUserGroups(userId);
        result.setData(data);
        return result;
    }

    @Operation(summary = "e.给用户分配用户组", description = "<font color='red'>不检查重复，可以先调用删除用户组接口，再调用本接口。</font>或者直接调用‘编辑用户用户组’接口")
    @PostMapping("/addUserGroups")
    public JsonResult addUserGroups(@Parameter(description = "用户ID") @RequestParam(value = "userId") String userId,
                                    @Parameter(description = "用户组ID列表，用逗号分隔") @RequestParam(value = "GroupIds") String GroupIds) {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(GroupIds)) {
            return JsonResult.Fail("common.paramError");
        }
        JsonResult result = JsonResult.Success("common.handleSuccess");
        result.setShow(false);
        groupService.addUserGroups(userId, GroupIds);
        //写日志
        logService.saveSystemLog(getComment(), "addUserGroups", userId, "GroupIds:" + GroupIds);
        return result;
    }

    @Operation(summary = "b.编辑用户用户组", description = "先清除该用户的旧用户组，再关联GroupIds中的用户组")
    @PostMapping("/editUserGroups")
    public JsonResult editUserGroups(@Parameter(description = "用户ID") @RequestParam(value = "userId") String userId,
                                     @Parameter(description = "用户组ID列表，用逗号分隔") @RequestParam(value = "GroupIds") String GroupIds) {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(GroupIds)) {
            return JsonResult.Fail("common.paramError");
        }
        JsonResult result = JsonResult.Success("common.handleSuccess");
        result.setShow(false);
        groupService.editUserGroups(userId, GroupIds);
        //写日志
        logService.saveSystemLog(getComment(), "editUserGroups", userId, "GroupIds:" + GroupIds);
        return result;
    }

    @Operation(summary = "c.删除某用户的所有用户组")
    @PostMapping("/delUserGroups")
    public JsonResult delUserGroups(@Parameter(description = "用户ID") @RequestParam(value = "userId") String userId) {
        if (StringUtils.isEmpty(userId)) {
            return JsonResult.Fail("common.paramError");
        }
        JsonResult result = JsonResult.Success("common.delSuccess");
        result.setShow(false);
        groupService.deleteUserGroups(userId);
        logService.saveSystemLog(getComment(), "delUserGroups", userId, "");
        return result;
    }

    @Operation(summary = "d.删除某用户拥有的一个用户组")
    @PostMapping("/delUserGroup")
    public JsonResult delUserGroup(@Parameter(description = "用户ID") @RequestParam(value = "userId") String userId,
                                   @Parameter(description = "用户组ID") @RequestParam(value = "GroupId") String GroupId) {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(GroupId)) {
            return JsonResult.Fail("common.paramError");
        }
        JsonResult result = JsonResult.Success("common.delSuccess");
        result.setShow(false);
        groupService.deleteUserGroup(userId, GroupId);
        //写日志
        logService.saveSystemLog(getComment(), "delUserGroup", userId, "GroupId:" + GroupId);
        return result;
    }

    @Override
    protected void handleFilter(QueryFilter filter) {
        String tenantId = ContextUtil.getCurrentTenantId();
        filter.addQueryParam("Q_g.status_I_NEQ", StatusEnum.deleted.getCode());
        if (StringUtils.isNotEmpty(tenantId)) {
            filter.addQueryParam("Q_g.tenant_id_S_EQ", tenantId);
        } else {
            filter.addQueryParam("Q_g.tenant_id_S_ISNULL", "1");
        }
    }

    @Operation(summary = "根据主键ID删除记录", description = "删除一条记录}")
    @PostMapping("del")
    @Override
    public JsonResult del(@RequestParam(value = "id") String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonResult.Fail("common.paramError");
        }
        groupService.deleteGroup(id);
        JsonResult result = JsonResult.Success("common.delSuccess");
        result.setShow(false);
        logService.saveSystemLog(getComment(), "delete", id, "");
        return result;
    }

    @Override
    public JsonResult save(@Validated @RequestBody Group entity, BindingResult validResult) throws Exception {
        if (entity == null || StringUtils.isEmpty(entity.getGroupName())) {
            return JsonResult.Fail("common.paramError");
        }
        String pkId = entity.getPkId();
        //新增
        if (StringUtils.isEmpty(pkId)) {
            entity.setSeq(1);
            entity.setTenantId(ContextUtil.getCurrentTenantId());
        } else {
            entity.setSeq(entity.getSeq() + 1);
        }
        //处理父节点相关信息
        String parentId = entity.getParentId();
        if (StringUtils.isEmpty(parentId)) {
            entity.setLevel(Constants.SHORT1);
        } else {
            //获取父节点信息
            var parent = groupService.getByValidId(parentId);
            if (parent == null) {
                return JsonResult.Fail("common.paramError");
            }
            int level = parent.getLevel() + 1;
            entity.setLevel((short) level);
            //计算路径
            String parentPath = parent.getPath();
            if (StringUtils.isEmpty(parentPath)) {
                entity.setPath(parentId);
            } else {
                entity.setPath(parentPath + "." + parentId);
            }
        }
        return super.save(entity, validResult);
    }

    @Override
    public BaseService getBaseService() {
        return groupService;
    }

    @Override
    public String getComment() {
        return "用户组";
    }
}